<?php
class sms_model_message extends Model {
	const PAGE_SIZE=25;	
	const MSG_T_ALL = 0;
	const MSG_T_FRIREQ = 1;
	const MSG_T_GIFT = 2;
	const MSG_T_SKILL = 3;
	const MSG_CITE = 4;
	/**
	 * 更新未读消息数常量定义
	 *
	 */
	const MSG_SMS_CNT = 1;
	const MSG_SYS_SMS_CNT = 2;
	const MSG_MESSAGE_CNT = 3;
	const MSG_COMMENT_CNT = 4;
	const MSG_SYS_FRIENDS = 5;
	const MSG_SYS_BUFF 	  = 6;
	const MSG_SYS_GIFT 	  = 7;
	
	var $msgType = array(
		self::MSG_T_ALL => 0, //所有消息
		self::MSG_T_FRIREQ => '[:friends|add:]', //好友请求
		self::MSG_T_GIFT => '[:gift:]', //礼物类型
		self::MSG_T_SKILL => '[:buff:]', // 技能类型
		self::MSG_CITE => '[:cite:]' //转帖类型
	);
	private $table_s = '';
	public function __construct(){
		parent::__construct();
		//$this->table = 'app_sms_message';
		$this->table = 'app_sms_ms';
		$this->table_s = 'app_sms_session';
	}
	
	public function add($arguments){
		$arguments = filter_params($arguments, 'sms_id', 'sender_id', 'sender_name', 'reciever_id', 'reciever_name', 'content', 'type', 'title');
		trim_params($arguments);
		$arguments['create_time'] = time();
		$arguments['is_deleted'] = 0;
		$this->updateSmsNums($arguments);
		return $this->db->insert($this->table, $arguments);
	}
	
	private   function updateSmsNums(&$param,$type=1){
		$sql = "UPDATE app_sms_count SET ";
		if($param['sender_id']==0 && $param['type']==0){
			$sql.= ' asc_sysann = asc_sysann+1';
			if(strpos($param['sender_name'],':friends|add:') !==false){
				$type = self::MSG_SYS_FRIENDS ;
			}
			elseif (strpos($param['sender_name'],':buff:') !==false){
				$type = self::MSG_SYS_BUFF  ;
			}
			elseif(strpos($param['sender_name'],':gift:') !==false){
				$type = self::MSG_SYS_GIFT   ;
			}
			else $type = self::MSG_SYS_SMS_CNT;
		}
		$data = $this->factory('sms_model_data');
		if(is_array($param['reciever_id']) && !empty($param['reciever_id'])){
			foreach ($param['reciever_id'] as $v){
				$data->updateSmsCount($v,$type,1);
			}
		}else{
			$data->updateSmsCount($param['reciever_id'],$type,1);
		}
		unset($data);
		return ;
	}
	
	public function setDelete($sms_id, $uid){
		$sql = "update ".$this->table." set is_deleted=1 where sms_id=&sms_id and uid=&uid";
		$params = array(
			'sms_id' 	=> 	$sms_id,
			'uid'		=>	$uid
		);
		return $this->db->query($sql, $params);
	}
	
	public function getList($sms_id){
		$sql = "select * from ".$this->table." where sms_id=&sms_id order by create_time";
		$params = array('sms_id'=>$sms_id);
		return $this->db->fetchAll($sql, $params);
	}
	
	
	/**
	 * 获取收件箱列表
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $page
	 * @param unknown_type $pageSize
	 */
	public function getOutBoxpage($uid,$page=1,$pageSize=PAGE_SIZE){
		$sql = 'SELECT a.sms_id,a.sms_title,a.sms_content,a.sms_sender,a.sms_senderid,a.sms_reciver,a.sms_reciverid,a.sms_pid,a.sms_total_num,a.sms_duplicate,a.sms_dateline  
		FROM '.$this->table.' a WHERE sms_senderid=&uid AND sms_isdelete=0 ORDER BY sms_id DESC';
		$params = array('uid'=>$uid);
		return $this->db->selectPageSimple($sql, $params, $page, $pageSize );
	}
	
	/**
	 * 获取收件箱列表
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $page
	 * @param unknown_type $pageSize
	 */
	public function getInBoxpage($uid,$page=1,$pageSize=PAGE_SIZE){
		$sql = 'SELECT a.sms_id,a.sms_title,a.sms_content,a.sms_sender,a.sms_senderid,a.sms_pid,a.sms_total_num,a.sms_dateline ,
				b.sms_id,b.sms_type,b.sms_lastdel_msid,b.sms_username,b.sms_readed,b.sms_uid
		FROM '.$this->table.' a,'.$this->table_s.' b 
		WHERE b.sms_uid = &uid AND a.sms_senderid!=&uid AND b.sms_last_msid = a.sms_id AND b.sms_last_msid>b.sms_lastdel_msid ORDER BY b.sms_last_msid DESC ';
		$params = array('uid'=>$uid);
		return $this->db->selectPageSimple($sql, $params, $page, $pageSize );
	}
	
	public function selectOutboxPage($uid, $page, $pageSize){
//		$sql = "
//SELECT m.id, m.sms_id, m.content, m.create_time, s.reciever_count, r.uid, r.username
//FROM app_sms_message m
//LEFT JOIN app_sms s ON m.sms_id = s.id
//LEFT JOIN app_sms_reciever r ON m.sms_id = r.sms_id
//WHERE m.uid = &uid
//AND m.is_deleted =0
//AND m.type =1
//AND r.uid <> &uid
//AND r.username <> &username
//GROUP BY m.id
//ORDER BY m.id DESC
//		";

//				$sql = "
//SELECT m.id, m.sms_id, m.content, m.create_time, s.reciever_count, m.sender_id, m.sender_name, m.reciever_id, m.reciever_name, s.message_count
//FROM app_sms_message m
//LEFT JOIN app_sms s ON m.sms_id = s.id
//WHERE m.sender_id = &uid
//AND m.is_deleted =0
//AND m.type =1
//GROUP BY m.id
//ORDER BY m.id DESC
//		";
		$sql = "SELECT m.id, m.sms_id, m.title, m.content, m.create_time, s.reciever_count, m.sender_id, m.sender_name, m.reciever_id, m.reciever_name, s.message_count, l. * 
FROM app_sms_message m
INNER JOIN app_sms s ON m.sms_id = s.id
LEFT JOIN app_sms_delete_log l ON m.id = l.msg_id AND m.sender_id = l.uid
WHERE m.sender_id = &uid
AND s.type =1
AND l.msg_id IS NULL 
ORDER BY m.id DESC   ";
		$params = array('uid'=>$uid);
		return $this->db->selectPageSimple($sql, $params, $page, $pageSize );
	}
	
	public function selectInboxPage($uid, $page, $pageSize){
		$sql = "SELECT m.id, m.sms_id, m.sender_id, m.sender_name, m.title, m.content, m.create_time, s.message_count, r.unread
from app_sms_message m
inner join app_sms_reciever r on m.id = r.last_msg_id
inner join app_sms s on m.sms_id = s.id
where r.uid=&uid and r.type=1 and r.is_refused=0 
order by r.last_msg_id desc";
		$params = array('uid'=>$uid);
		return $this->db->selectPageSimple($sql, $params, $page, $pageSize );
	}
	
/*	public function select($sms_id, $uid){
		$sql = "select m.*, l.uid del_uid 
from ".$this->table." m 
left join app_sms_delete_log l on m.id=l.msg_id and l.uid=&uid 
where m.sms_id=&sms_id";
		$params = array('sms_id'=>$sms_id, 'uid'=>$uid);
		return $this->db->fetchAll($sql, $params);
	}	*/

	
	
	public function selectById($id){
		$sql = "select * from ".$this->table." where id=&id and is_deleted=0";
		$params = array('id'=>$id);
		return $this->db->fetchRow($sql, $params);
	}
	
	public function selectSysInboxPage($uid, $page, $pageSize,$type = ''){
		$msgtype = '';
		if($type!=='' && array_key_exists($type,$this->msgType)){
			$msgtype = $this->parseSenderNames($this->msgType[$type]);
		}
		$sql = "SELECT m.id, m.sms_id, m.sender_id, m.sender_name, m.title, m.content, m.create_time, s.message_count, s.target, r.unread
FROM `app_sms_message` m
INNER JOIN `app_sms_reciever` r ON r.sms_id = m.sms_id
INNER join app_sms s on s.id = m.sms_id
WHERE r.uid = &uid
AND m.type = 0 ".($msgtype?'AND m.sender_name = \''.$msgtype.' \'':'')." and m.is_deleted = 0
ORDER BY m.id DESC ";
		$params = array('uid'=>$uid);
		return $this->db->selectPageSimple($sql, $params, $page, $pageSize );
	}
	private function parseSenderNames($str){
		$regex = "`\[\:([a-z0-9]+)(?:\|[a-z0-9]+)?\:\]`";
		$flag = preg_match($regex, $str, $match);
		if($flag){
			return $match[0];
		}else{
			return NULL;
		}
	}
	public function remove($id, $uid,$delAll = false){
//		$sql = "update ".$this->table." set is_deleted = 1 where id=&id and sender_id=&uid";
//		$params = array('id'=>$id, 'uid'=>$uid);
//		return $this->db->query($sql, $params);
		$sql = "insert ignore into app_sms_delete_log values ";
		if($delAll===true){
			$sql = "REPLACE INTO app_sms_delete_log SELECT sms_id,uid FROM app_sms_reciever r WHERE r.uid=&uid ";
			$params = array('uid'=>$uid);
			return $this->db->query($sql, $params);
		}
		if(is_array($id) && !empty($id)){
			foreach ($id as $v){
				$sql.=' (\''.$v.'\','.$uid.'),';
			}
			$sql = substr($sql,0,-1);
			return $this->db->query($sql,array());
		}
		$sql .= " (&msg_id, &uid) ";
		$params = array('msg_id'=>$id, 'uid'=>$uid);
		return $this->db->query($sql, $params);
	}
	
	public function removeSystem($id, $uid,$delAll=false){
		if($delAll==true){
			$sql = "update ".$this->table." set is_deleted = 1 where type=0 and reciever_id=&uid";
			$params = array('uid'=>$uid);
			return $this->db->query($sql, $params);
		}
		$sql = "update ".$this->table." set is_deleted = 1 where id ";
		if(is_array($id) && !empty($id)){
			$smsid = ' (';
			foreach ($id as $v){
				$smsid .=$v.',';
			}
			$smsid = substr($smsid,0,-1).')';
			$sql .= " IN $smsid and reciever_id=&uid";
			$params = array('id'=>$smsid, 'uid'=>$uid);
			return $this->db->query($sql, $params);
		}
		$sql .= " = &id and reciever_id=&uid";
		$params = array('id'=>$id, 'uid'=>$uid);
		return $this->db->query($sql, $params);

//		$sql = "insert ignore into app_sms_delete_log values (&msg_id, &uid) ";
//		$params = array('msg_id'=>$id, 'uid'=>$uid);
//		return $this->db->query($sql, $params);
	}
	
	public function selectDumpPage($uid, $page, $pageSize){
		$sql = "select m.* from app_sms_message m
inner join app_sms_delete_log l on m.id = l.msg_id and l.uid=&uid
order by m.id desc
		 ";
		$params = array('uid'=>$uid);
		return  $this->db->selectPageSimple($sql,$params,$page,$pageSize);
	}
	
	
}

